//
//  CZComposeViewController.swift
//  微博08
//
//  Created by apple on 16/3/6.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

enum ToolBarTagType: Int {
    case picture = 0
    case trend = 1
    case mention = 2
    case emoticon = 3
    case add = 4
}

/*
    iOS9 UIStackView
*/
class CZComposeViewController: UIViewController {
    
    private let statusMaxLength = 25
    
    /// 是否显示照片选择器的view
    private var showPhotoSelectorView: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        prepareUI()
        
        // 监听键盘的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        self.addChildViewController(photoSelectorVC)
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 照片选择器没有显示的时候才需要弹出键盘
        if !showPhotoSelectorView {
            textView.becomeFirstResponder()
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /*
    弹出
    notification: NSConcreteNotification 0x7fd7270c75a0 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";     // 键盘开始的位置
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";   // 键盘结束的位置
        UIKeyboardIsLocalUserInfoKey = 1;
    }}
    
    隐藏
    notification: NSConcreteNotification 0x7fd724dedb60 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
    }}
    */
    
    func keyboardWillChangeFrame(notification: NSNotification) {
//        print("notification: \(notification)")
        
        // 动画时间
        let duration = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        
        // 键盘最终的frame
        let frame = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        
        // 设置toolBar的位置,更改底部约束
        // 底部的距离 = 屏幕的高度 - 键盘frame.origin.y
        let toolBarBottomCon = -(UIScreen.height - frame.origin.y)
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(toolBarBottomCon)
        }
        
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    private func prepareUI() {
        setupNavigationBar()
        setupTextView()
        setupPhotoSelector()
        setupToolBar()
        setupLengthTipLabel()
    }
    
    private func setupPhotoSelector() {
        let photoSelectorView = photoSelectorVC.view
        // 添加子控件
        view.addSubview(photoSelectorView)
        
        // 添加约束
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(view)
            make.height.equalTo(view).multipliedBy(0.6)
            make.bottom.equalTo(view).offset(UIScreen.height * 0.6)
        }
    }
    
    /// 设置长度label
    private func setupLengthTipLabel() {
        // 添加子控件
        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.text = String(statusMaxLength)
        lengthTipLabel.sizeToFit()
        
        // 添加约束6
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(view).offset(-4)
            make.bottom.equalTo(toolBar.snp_top).offset(-4)
        }
    }
    
    /// 设置textView
    private func setupTextView() {
        // 添加子控件
        view.addSubview(textView)
        
        // 添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        
        // 自动调整scrollViewInsets
        // 前提1:scrollView或子类所在的view是在导航栏里面
        // 前提2:scrollView或子类必须是控制器的view或者scrollView或子类是控制器view的第一个子view,在依次循环
//        automaticallyAdjustsScrollViewInsets = true
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        // 添加子控件
        view.addSubview(toolBar)
        
        // 添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]]
        
        // 创建items
        toolBar.items = [UIBarButtonItem]()
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            let item = UIBarButtonItem(imageName: imageName)
            
            toolBar.items?.append(item)
            
            // 获取UIBarButtonItem里面的按钮
            let button = item.customView as! UIButton
            
            // 点击事件名称
            let action = dict["action"]!
            
            // 添加点击事件
            /// 可以直接放入String,如果是变量或常量需要使用Selector
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            // 添加弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        // 删除最后一根弹簧
        toolBar.items?.removeLast()
    }
    
    /**
      设置导航栏
     */
    private func setupNavigationBar() {
        setupBarButonItem()
        setupTitleView()
    }
    
    /**
     设置导航栏左右按钮
     */
    private func setupBarButonItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        // 让barButton不可用
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    /**
     设置导航栏title
     */
    private func setupTitleView() {
        let prefix = "发微博"
        // 测试
//        CZUserAccountViewModel.sharedInstance.userAccount?.screen_name = nil
        if let name = CZUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            // 有名称,拼接名称 \n 换行
            let title = prefix + "\n" + name
            
            // 创建label
            let titleLabel = UILabel()
            titleLabel.font = UIFont.systemFontOfSize(14)
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = NSTextAlignment.Center
            
//            titleLabel.text = title
            
            let attrText = NSMutableAttributedString(string: title)
            
            // 在整个字符串中查找name的range
            let range = (title as NSString).rangeOfString(name)
            
            // 添加属性
            attrText.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
            
            titleLabel.attributedText = attrText
            
            // 适配大小: 注意需要先设置label的text或attributedText
            titleLabel.sizeToFit()
            
            navigationItem.titleView = titleLabel
        } else {
            // 没有名称
            navigationItem.title = prefix
        }
    }
    
    // MARK: - 按钮点击事件
    /// 图片
    @objc private func picture() {
        // 键盘退下
        textView.resignFirstResponder()
        
        // 照片选择器上来,底部重合
        photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(0)
            showPhotoSelectorView = true
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func trend() {
        print("点击#")
    }
    
    @objc private func mention() {
        print("点击@")
    }
    
    /*
        1.直接设置inputView是不会切换
        2.表情键盘是用系统的还是用自定的,看弹出前那一刻,如果inputView == nil,弹系统键盘, inptuView有值,就弹对应的键盘
    */
    @objc private func emoticon(button: UIButton) {
        print("点击表情 textView.inputView : \(textView.inputView)")
        
        // 1.将键盘退下
        textView.resignFirstResponder()
        
        // 2.设置键盘, 当前是系统键盘就切换成自定义键盘,如果是自定义键盘就切换成系统键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        let image: UIImage?
        let highlightedImage: UIImage?
        // 切换按钮的图片
        if textView.inputView == nil {
            image = UIImage(named: "compose_emoticonbutton_background")
            highlightedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
        } else {
            image = UIImage(named: "compose_keyboardbutton_background")
            highlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
        }
        
        button.setImage(image, forState: UIControlState.Normal)
        button.setImage(highlightedImage, forState: UIControlState.Highlighted)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            // 3.在将键盘弹出
            self.textView.becomeFirstResponder()
        }
    }
    
    @objc private func add() {
        print("点击+")
    }
    
    /// 取消
    @objc private func close() {
        SVProgressHUD.dismiss()
        
        // 退回键盘,取消第一响应者
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发送微博
    func send() {
        // 获取要发布的内容
        let status = textView.emoticonText()
        
        // 判断微博长度
        let length = textView.emoticonText().characters.count
        
        // 计算文本剩余长度
        let lastLength = statusMaxLength - length
        if lastLength < 0 {
            SVProgressHUD.showInfoWithStatus("微博超出长度", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        SVProgressHUD.showWithStatus("正在发布微博", maskType: SVProgressHUDMaskType.Black)
        
        // 发布微博
        CZStatusViewModel.sendStatus(status, image: photoSelectorVC.photos.first) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                print("error \(error)")
                return
            }
            
            // 发布微博成功了
            SVProgressHUD.showWithStatus("发布微博成功", maskType: SVProgressHUDMaskType.Black)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(400 * USEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.close()
            })
        }
        
    }
    
    // MARK: - 懒加载
    /// toolBar
    private lazy var toolBar: UIToolbar = {
        let toolBar = UIToolbar()
        
        
        return toolBar
    }()
    
    /*
        iOS中的输入控件:
            1.UITextField
                a.有占位文本
                b.只有一行
                c.不能滚动
            
            2.UITextView
                a.没有占位文本
                b.可以显示多行
                c.可以滚动
    */
    
    // textView
    private lazy var textView: CZPlaceholderTextView = {
        let tv = CZPlaceholderTextView()
        tv.alwaysBounceVertical = true
        tv.font = UIFont.systemFontOfSize(18)
        
        // textView键盘的退出方式
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.placeholder = "分享新鲜事..."
        
        // 设置代理监听textView文字的改变
        tv.delegate = self
        
        return tv
    }()
    
    /// 表情键盘
    private lazy var emoticonKeyboard: CZEmoticonKeyboard = {
        let view = CZEmoticonKeyboard(frame: CGRect(origin: CGPointZero, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 216)))
        
        view.textView = self.textView
        
        return view
    }()
    
    /// 微博长度提示label
    private lazy var lengthTipLabel: UILabel = UILabel(textColor: UIColor.lightGrayColor(), font: 11)
    
    /// 照片选择控制器, 当一个控制器的view成为另一个控制器的view的子view,那么这个控制器最好也成为另一个控制器的子控制器
    private lazy var photoSelectorVC: CZPhotoSelectorController = CZPhotoSelectorController()
}

// MARK: - 扩展 CZComposeViewController 实现 UITextViewDelegate
extension CZComposeViewController: UITextViewDelegate {
    /// 监听文字的改变
    func textViewDidChange(textView: UITextView) {
        // 有文字rightBarButtonItem可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 获取现有长度
        let length = textView.emoticonText().characters.count
        
        // 计算文本剩余长度
        let lastLength = statusMaxLength - length
        lengthTipLabel.text = String(lastLength)
        
        // 设置颜色
        lengthTipLabel.textColor = lastLength < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
